package com.wxtf.platform.plugins.system_config;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wxtf.platform.interfaces.CommonsCallProvider;
import com.wxtf.platform.plugins.role.RoleAction;
import com.wxtf.platform.plugins.user.UserBean;
import com.wxtf.platform.supers.LogicBase;
import com.wxtf.platform.tools.AccessDataBaseUtil;
import com.wxtf.platform.tools.ConstantInfoHelper;
import com.wxtf.platform.tools.FormatUtil;

public class SystemConfig extends LogicBase implements CommonsCallProvider{

	private static Log log = LogFactory.getLog(RoleAction.class);

	public SystemConfig(String jsonArray) {

	}

	@Override
	public Object onInit(Object jsonArray) {
		return null;
	}

	@Override
	public Object onCreate(Object jsonArray) {
		return null;
	}

	@Override
	public Object onDestory(Object jsonArray) {
		return null;
	}

	@Override
	public Object run() {
		Object msg = "";
		try {
			if ("queryPage".equals(this.getMethodName())) {// 列表
				msg = this.select(this.getExtendData());
				return msg.toString();
			} else if ("save".equals(this.getMethodName())) {// 添加
				msg = this.insert(this.getLogicData());
			} else if ("update".equals(this.getMethodName())) {// 修改
				msg = this.update(this.getLogicData());
			} else if ("delete".equals(this.getMethodName())) {// 删除
				msg = this.delete(this.getLogicData());
			} else {
				msg = "\"没有【" + this.getMethodName() + "】该方法\"";
			}
			if(msg == null || "[null]".equals(msg)){
				msg = "\"\"";
			}
			msg = ConstantInfoHelper.generateJSONString(msg.toString());
			//log.info(this.getClass().getName() +":"+this.getMethodName() + " -> " + msg);
		} catch (Exception e) {
			msg = "操作失败，请联系管理员";
			msg = ConstantInfoHelper.generateJSONString(ConstantInfoHelper.JSON_HEAD, ConstantInfoHelper.getFailResultDetail(msg.toString()), false);
			log.error(e, e);
		} finally {
			this.clear();
		}
		return msg.toString();
	}

	@Override
	public Object select(Object jsonArray) throws Exception {
		sql = " from t_system_config";
		UserBean user = (UserBean)(this.getRequest()).getSession().getAttribute("userBean");
		String sc_uid = user.getUserId();
		if(!"0".equals(sc_uid)){
			sql += " where sc_uid = '"+sc_uid+"'";
		}
		HttpServletRequest request = this.getRequest();
		String sortname = request.getParameter("sortname");
		String sortorder = request.getParameter("sortorder");
		if(sortname!=null&&sortname!=null) {
			sql +=" order by "+sortname+" "+sortorder+"";
		}
		String countSql = "select count(sc_uuid)" + sql;
		String querySql = "select sc_uuid,sc_uid,sc_key,sc_value,sc_marked,sc_write_time " + sql + " order by sc_key";
		return AccessDataBaseUtil.query4SQLPagging(fields, countSql, querySql, this.getPage(), this.getPagesize(), null);
	}

	private String[] fields = { "sc_uuid", "sc_uid","sc_key", "sc_value", "sc_marked" ,"sc_write_time"};
	@Override
	public Object insert(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		Object[] obj = new Object[fields.length];
		UserBean user = (UserBean)(this.getRequest()).getSession().getAttribute("userBean");
		String sc_uid = user.getUserId();
		String sc_write_time = FormatUtil.getCurentDate();		
		obj[0] = AccessDataBaseUtil.getPKUUID();
		obj[1] = sc_uid;
		obj[2] = jsonObject.getString("esc_key");
		obj[3] = jsonObject.getString("esc_value");
		obj[4] = jsonObject.getString("esc_marked");
		obj[obj.length - 1] = sc_write_time;
		String sc_key = jsonObject.getString("esc_key");
		//参数名为exceeds时，修改内存中的数据
		if(obj[2].equals("exceeds"))
		{
			user.getGlobalMap().put("exceeds",obj[3].toString());
		}
		String sql1 = "select count(*) from t_system_config where sc_key='"+sc_key+"' and sc_uid='0'";
		List<Object> ls = AccessDataBaseUtil.query4List(sql1,new Object[]{});
		int hasId = Integer.parseInt(ls.get(0).toString());
		if(hasId>0){
			return "\"参数名称不可以跟系统参数名称重复\"";
		}
		
		sql = "insert into t_system_config(sc_uuid,sc_uid,sc_key,sc_value,sc_marked,sc_write_time) values(?,?,?,?,?,?)";
		AccessDataBaseUtil.executeSQLUpdate(sql, obj);
		return "\"新建成功\"";
	}

	@Override
	public Object update(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		Object[] obj = new Object[3];
		obj[0] = jsonObject.getString("sc_value");
		obj[1] = jsonObject.getString("sc_marked");
		obj[2] = jsonObject.getString("sc_uuid");
		sql = "update t_system_config set sc_value = '"+obj[0]+"',sc_marked = '"+obj[1]+"' where sc_uuid = '"+obj[2]+"'";
		
		//参数名为exceeds时，修改内存中的数据
		String sc_key  = jsonObject.getString("sc_key");//参数名

		if(sc_key.equals("exceeds"))
		{
			UserBean user = (UserBean)this.getRequest().getSession().getAttribute("userBean");
			user.getGlobalMap().put("exceeds",obj[0].toString());
		}
		String[] sqls = { sql};
		AccessDataBaseUtil.executeSQLUpdate(sqls);
		return "\"修改成功\"";
	}

	@Override
	public Object delete(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String id = jsonObject.getString("ids");
		String[] ids = id.split(",");
		String sql = "delete from t_system_config where sc_uuid = ?";
		AccessDataBaseUtil.deleteByIds(sql, ids);
		return "\"删除成功\"";
	}
	
	@Override
	public Object updateBatch(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object recordCount(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object setRequest(HttpServletRequest request) throws Exception {
		this.request = request;
		return request;
	}
}
